<?php
namespace backend\controllers;
use backend\models\AgentAreaModel;
use backend\models\CouponModel;
use backend\models\StatisticsAreaTeacherModel;
use backend\models\StatisticsAreaUserModel;
use backend\models\StatisticsCourseModel;
use backend\models\StatisticsCourseVideoModel;
use backend\models\StatisticsPaidModel;
use backend\models\StatisticsSqOldUserPriceModel;
use backend\models\StatisticsSqUserCashModel;
use backend\models\StatisticsTeacherModel;
use backend\models\StatisticsUserCouponModel;
use backend\models\StatisticsUserModel;
use common\base_models\kds\AgentArea;
use Yii;
use backend\base\BaseController;

/**
 * 统计管理
 * Class StatisticsController
 * @package backend\controllers
 */
class StatisticsController extends BaseController
{
    public $time = 0;
    public $start_time = 0;
    public $end_time = 0;
    public $dimension;
    public $input_date;
    public $dimension_group = [1=>'"%m月%d日"',2=>'"%Y年%u周"',3=>'"%Y年%m月"',4=>'FROM_UNIXTIME(`date`, concat(FROM_UNIXTIME(date, "%Y年"),FLOOR((FROM_UNIXTIME(date, "%m")+2)/3),"季度"))',5=>'"%Y年"'];

    public function init()
    {
        parent::init();
        if(Yii::$app->request->get('exporting')){
            return true;
        }
        $this->time = time();
        $this->dimension = Yii::$app->request->get('dimension',1);
        $this->input_date = Yii::$app->request->get('input_date','');
        //日期搜索
        if($this->input_date){
            $input_date_arr = explode('~',$this->input_date);
            if(count($input_date_arr) == 2){
                $this->start_time = (int)strtotime($input_date_arr[0]);
                $this->end_time = (int)strtotime($input_date_arr[1]);
            }
        }else{
            //默认搜索最近1月
            $this->start_time = strtotime('-1 month -1 day',$this->time);
            $this->end_time = $this->time - 86400;
        }
        $this->input_date = date('Y-m-d',$this->start_time).' ~ '.date('Y-m-d',$this->end_time);
    }

    /**
     * 注册用户统计
     */
    public function actionUser()
    {
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsUserModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(total_num) total_num,sum(increment_num) increment_num,max(id) id'])->where($condition)->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsUserModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,total_num,increment_num'])->where($condition)->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('user',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date]);
    }

    /**
     * 注册老师统计
     */
    public function actionTeacher()
    {
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsTeacherModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(total_num) total_num,sum(increment_num) increment_num,max(id) id'])->where($condition)->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsTeacherModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,total_num,increment_num'])->where($condition)->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('teacher',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date]);
    }

    /**
     * 付费金额统计
     */
    public function actionPaid()
    {
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsPaidModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(total_num) total_num,sum(increment_num) increment_num,max(id) id'])->where($condition)->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsPaidModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,total_num,increment_num'])->where($condition)->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('paid',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date]);
    }

    /**
     * 课程统计
     */
    public function actionCourse()
    {
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsCourseModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(total_num) total_num,sum(increment_num) increment_num,max(id) id'])->where($condition)->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsCourseModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,total_num,increment_num'])->where($condition)->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('course',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date]);
    }

    /**
     * 视频统计
     */
    public function actionCourseVideo()
    {
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsCourseVideoModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(total_num) total_num,sum(increment_num) increment_num,sum(total_duration) total_duration,sum(increment_duration) increment_duration,sum(total_play_num) total_play_num,sum(increment_play_num) increment_play_num,sum(total_play_duration) total_play_duration,sum(increment_play_duration) increment_play_duration,max(id) id'])->where($condition)->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsCourseVideoModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,total_num,increment_num,total_duration,increment_duration,total_play_num,increment_play_num,total_play_duration,increment_play_duration'])->where($condition)->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('course-video',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date]);
    }

    /**
     * 卡券统计
     */
    public function actionUserCoupon()
    {
        $coupon_id = $this->get('coupon_id');
        $coupon = CouponModel::find()->orderBy('is_expire asc,id desc')->all();
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsUserCouponModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(create_num) create_num,sum(use_num) use_num,sum(expire_num) expire_num,max(id) id'])->where($condition)->andFilterWhere(['coupon_id'=>$coupon_id])->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsUserCouponModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,create_num,use_num,expire_num'])->where($condition)->andFilterWhere(['coupon_id'=>$coupon_id])->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('user-coupon',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date,'coupon_id'=>$coupon_id,'coupon'=>$coupon]);
    }

    /**
     * 区域or代理商 - 注册用户统计
     */
    public function actionAgentUser()
    {
        $area_list = $country_ids = $group = [];
        $agent_id = $this->get('agent_id','');
        $country_id = $this->get('country_id','');
        if($agent_id){
            if($country_id){
                $country_ids = [$country_id];
            }else{
                $country_ids = AgentArea::find()->select('country')->where(['agent_id'=>$agent_id])->column();
            }
            $area_list = AgentAreaModel::getMyCountryList($agent_id);
        }
        $condition = '`date` between '.$this->start_time.' and '.$this->end_time;
        $list_user = StatisticsAreaUserModel::find()
            ->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[1].') date_group,sum(`num`) as total_num'])
            ->where($condition)
            ->andFilterWhere(['in','country',$country_ids])
            ->groupBy('`date`')
            ->orderBy('id asc')
            ->asArray()->all();
        $list_teacher = StatisticsAreaTeacherModel::find()
            ->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[1].') date_group,sum(`num`) as total_num'])
            ->where($condition)
            ->andFilterWhere(['in','country',$country_ids])
            ->groupBy('`date`')
            ->orderBy('id asc')
            ->asArray()->all();
        $list_user = $this->listToData($list_user);
        $list_teacher = $this->listToData($list_teacher);
        return $this->render('agent-user',['list_user'=>$list_user,'list_teacher'=>$list_teacher,'input_date'=>$this->input_date,'area_list'=>$area_list,'country_id'=>$country_id,'agent_id'=>$agent_id]);
    }


    /**
     * 统计暑假包邀请中奖统计
     */
    public function actionSqUserCash()
    {
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsSqUserCashModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(total_num) total_num,sum(increment_num) increment_num,sum(total_price) total_price,sum(increment_price) increment_price,max(id) id'])->where($condition)->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsSqUserCashModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,total_num,increment_num,total_price,increment_price'])->where($condition)->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('sq-user-cash',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date]);
    }

    /**
     * 统计暑假包邀请中奖统计
     */
    public function actionSqOldUserPrice()
    {
        $condition = 'date between '.$this->start_time.' and '.$this->end_time;
        if($this->dimension != 1){
            $list = StatisticsSqOldUserPriceModel::find()->select(['FROM_UNIXTIME(`date`, '.$this->dimension_group[$this->dimension].') date_group,sum(total_num) total_num,sum(increment_num) increment_num,sum(total_price) total_price,sum(increment_price) increment_price,max(id) id'])->where($condition)->groupBy('date_group')->orderBy('id asc')->asArray()->all();
        }else{
            $list = StatisticsSqOldUserPriceModel::find()->select(['FROM_UNIXTIME(`date`,'.$this->dimension_group[$this->dimension].') date_group,total_num,increment_num,total_price,increment_price'])->where($condition)->orderBy('id asc')->asArray()->all();
        }
        $data = $this->listToData($list);
        return $this->render('sq-old-user-price',['data'=>$data,'dimension'=>$this->dimension,'input_date'=>$this->input_date]);
    }

    /**
     * 数据结果转换
     */
    protected function listToData($list)
    {
        if(!$list){
            return [];
        }
        foreach($list as $item){
            foreach($item as $k => $v){
                if(!in_array($k,['date_group','id'])){
                    $data[$k][] = $item[$k];
                }
            }
            $data['times'][] = '"'.$item['date_group'].'"';
        }
        foreach($data as $k => $v){
            $data[$k] = implode(',',$v);
        }
        return $data;
    }
}

//$start_time = strtotime('2017-05-01');
//$total_num=0;
//for($i=1;$i<10000;$i++){
//    if($start_time > time()){
//        break;
//    }
//    $incr_num = mt_rand(3*$i,8*$i);
//    $total_num +=$incr_num;
//    $data[]=[2,1,$incr_num,$total_num,$start_time];
//    $start_time += 86400;
//}
//Yii::$app->db->createCommand()->batchInsert('statistics', ['type','dimension','incr_num','total_num','create_time'], $data)->execute();
?>